package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import com.tiancheng.trade.settlement.mapper.settlement.ClearBankDetailCmbMapper;
import com.tiancheng.trade.settlement.model.settlement.ClearBankDetailCmb;
import com.tiancheng.trade.settlement.service.settlement.IClearBankDetailCmbService;
import com.tiancheng.trade.settlement.util.ExcelUtil;
import com.tiancheng.trade.settlement.util.ObjectConvertUtil;
import com.tiancheng.trade.settlement.vo.settlement.admin.ClearDetailCmbExportQueryVO;
import com.tiancheng.trade.settlement.vo.settlement.admin.ClearDetailCmbQueryVO;
import com.tiancheng.trade.settlement.vo.settlement.admin.res.ClearDetailCmbExportResVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 清分明细（招行）
 */
@Service
public class ClearBankDetailCmbService implements IClearBankDetailCmbService {

    @Autowired
    ClearBankDetailCmbMapper clearBankDetailCmbMapper;

    /**
     * 查询清分明细
     *
     * @param clearDetailCmbExportQueryVo 查询条件
     * @return
     */
    private List<ClearBankDetailCmb> getClearBankDetailCmbForExport(ClearDetailCmbExportQueryVO clearDetailCmbExportQueryVo) {
        QueryWrapper<ClearBankDetailCmb> conditions = new QueryWrapper<>();
        conditions.select("pay_time", "clear_batch_no", "sub_mch_id", "order_id", "bank_order_id", "sub_order_id", "clear_amount", "pay_acct_name", "col_acct_name");
        if (StringUtils.isNotBlank(clearDetailCmbExportQueryVo.getBatchDateBegin())) {
            conditions.ge("accounts_file_date", clearDetailCmbExportQueryVo.getBatchDateBegin().replace("-", ""));
        }
        if (StringUtils.isNotBlank(clearDetailCmbExportQueryVo.getBatchDateEnd())) {
            conditions.lt("accounts_file_date", clearDetailCmbExportQueryVo.getBatchDateEnd().replace("-", "") + "235959");
        }
        return clearBankDetailCmbMapper.selectList(conditions);
    }

    /**
     * 分页查询
     *
     * @param clearDetailCmbQueryVo 查询条件
     * @return
     */
    public PageInfo findPageList(ClearDetailCmbQueryVO clearDetailCmbQueryVo) {
        int page = clearDetailCmbQueryVo.getCurrentPage();
        int limit = clearDetailCmbQueryVo.getPageSize();
        QueryWrapper<ClearBankDetailCmb> conditions = new QueryWrapper<>();
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getClearBatchNo())) {
            conditions.eq("clear_batch_no", clearDetailCmbQueryVo.getClearBatchNo());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getSubMchId())) {
            conditions.eq("sub_mch_id", clearDetailCmbQueryVo.getSubMchId());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getOrderId())) {
            conditions.eq("order_id", clearDetailCmbQueryVo.getOrderId());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getBankOrderId())) {
            conditions.eq("bank_order_id", clearDetailCmbQueryVo.getBankOrderId());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getSubOrderId())) {
            conditions.eq("sub_order_id", clearDetailCmbQueryVo.getSubOrderId());
        }
        if (clearDetailCmbQueryVo.getClearAmount() != null) {
            conditions.eq("clear_amount", clearDetailCmbQueryVo.getClearAmount());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getPayAcctName())) {
            conditions.eq("pay_acct_name", clearDetailCmbQueryVo.getPayAcctName());
        }
        if (StringUtils.isNotBlank(clearDetailCmbQueryVo.getColAcctName())) {
            conditions.eq("col_acct_name", clearDetailCmbQueryVo.getColAcctName());
        }
        if (clearDetailCmbQueryVo.getPayTimeBegin() != null) {
            conditions.ge("pay_time", clearDetailCmbQueryVo.getPayTimeBegin());
        }
        if (clearDetailCmbQueryVo.getPayTimeEnd() != null) {
            conditions.lt("pay_time", clearDetailCmbQueryVo.getPayTimeEnd().plusDays(1));
        }
        PageInfo<ClearBankDetailCmb> pageInfo = clearBankDetailCmbMapper.find(conditions, page, limit);
        PageInfo<ClearDetailCmbExportResVO> pageInfoRes = new PageInfo<>();
        pageInfoRes.setList(getClearDetailCmbResDataForQuery(pageInfo.getList()));
        pageInfoRes.setPagination(pageInfo.getPagination());
        return pageInfoRes;
    }

    /**
     * 导出
     *
     * @param clearDetailCmbExportQueryVo 查询条件
     */
    public void export(ClearDetailCmbExportQueryVO clearDetailCmbExportQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<ClearBankDetailCmb> list = getClearBankDetailCmbForExport(clearDetailCmbExportQueryVo);
        List<Map<String, Object>> mapList = listConvert(getClearDetailCmbExportResData(list));
        String fileName = "CmbClearDetail.xlsx";
        String[] title = {"订单日期", "清分批号", "子商户号", "外部订单号", "招行订单号", "子订单号", "清分金额", "付款方名称", "收款方名称"};
        Workbook workbook = ExcelUtil.buildWorkbook("招行清分明细", title, mapList);
        ExcelUtil.exportExcle(request, response, workbook, fileName);
    }

    /**
     * 数据转换
     *
     * @param list
     * @return
     */
    private List<Map<String, Object>> listConvert(List<ClearDetailCmbExportResVO> list) {
        List<Map<String, Object>> list_map = new ArrayList<>();
        try {
            for (ClearDetailCmbExportResVO t : list) {
                Field[] fields = t.getClass().getDeclaredFields();
                Map<String, Object> m = new LinkedHashMap<>();
                for (Field field : fields) {
                    String keyName = field.getName();
                    PropertyDescriptor pd = new PropertyDescriptor(keyName, t.getClass());
                    Method getMethod = pd.getReadMethod();// 获得getter方法
                    Object o = getMethod.invoke(t);// 执行get方法返回一个Object
                    m.put(keyName, o);
                }
                list_map.add(m);
            }
            return list_map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取并转换清分数据（分页查询）
     *
     * @param list 清分数据
     * @return
     */
    private List<ClearDetailCmbExportResVO> getClearDetailCmbResDataForQuery(List<ClearBankDetailCmb> list) {
        List<ClearDetailCmbExportResVO> listRes = new ArrayList<>();
        for (ClearBankDetailCmb summaryCmb : list) {
            ClearDetailCmbExportResVO resVo = ObjectConvertUtil.convert(summaryCmb, ClearDetailCmbExportResVO.class).get();
            resVo.setClearAmount(summaryCmb.getClearAmount().toString());
            resVo.setPayTime(DateTimeUtil.format(summaryCmb.getPayTime(), "yyyyMMdd"));
            listRes.add(resVo);
        }
        return listRes;
    }

    /**
     * 获取并转换清分数据（导出）
     *
     * @param list 清分数据
     * @return
     */
    private List<ClearDetailCmbExportResVO> getClearDetailCmbExportResData(List<ClearBankDetailCmb> list) {
        List<ClearDetailCmbExportResVO> listRes = new ArrayList<>();
        for (ClearBankDetailCmb summaryCmb : list) {
            ClearDetailCmbExportResVO resVo = ObjectConvertUtil.convert(summaryCmb, ClearDetailCmbExportResVO.class).get();
            BigDecimal clearAmount = new BigDecimal(summaryCmb.getClearAmount());
            resVo.setClearAmount(clearAmount.divide(new BigDecimal(100)).toString());
            resVo.setPayTime(DateTimeUtil.format(summaryCmb.getPayTime(), "yyyyMMdd"));
            listRes.add(resVo);
        }
        return listRes;
    }

}
